package com.leung.queue.impl;


import com.leung.queue.Queue;

import java.util.Iterator;

/**
 * @author 丨一
 * @version 1.0
 * @title QueueByArrayList
 * @description: 基于链表的环形数组(队列) -> 普通数组作为数组出队时效率比较低 -> 环形数组改造
 * @date 2024/10/31 15:53
 */
public class QueueByArrayList<E> implements Iterable<E>, Queue<E> {
    //头尾指针法,尾指针当前指向的地址不能存储数据
    private final E[] array;
    private int head = 0;
    private int tail = 0;
    
    //定义队列的容量
    public QueueByArrayList(int capacity) {
        this.array = (E[]) new Object[capacity + 1];
    }

    @Override
    public boolean offer(E element) {
        if (isfull()) {
            return false;
        } else {
            array[tail] = element;
            tail = (tail + 1) % array.length;
            return true;
        } 
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        } else {
            E element = array[head];
            head = (head + 1) % array.length;
            return element;
        } 
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[head];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    /*
    判满
     */
    public boolean isfull() {
        return (tail + 1) % array.length == head;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<>() {
            //维护一个本地标记,使每个迭代器都能独立
            int thisHead = head;
            
            @Override
            public boolean hasNext() {
                return thisHead != tail;
            }

            @Override
            public E next() {
                E element = array[thisHead];
                thisHead = (thisHead + 1) % array.length;
                return element;
            }
        };
    }
}
